﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Linq;
using Common;

namespace DO.Workflows
{
    [DataContract]
    public class Run
    {
        #region props
        [DataMember]
        public Guid RunID { get; set; }
        [DataMember]
        public Guid WorkflowID { get; set; }
        [DataMember]
        public DateTime? SubmitTime { get; set; }
        [DataMember]
        public DateTime? ReceiveTime { get; set; }
        [DataMember]
        public DateTime? StartTime { get; set; }
        [DataMember]
        public DateTime? FinishTime { get; set; }
        [DataMember]
        public List<GlobalVariable> Variables { get; set; }
        #endregion

        public Run()
        {
            RunID = Guid.Empty;
            WorkflowID = Guid.Empty;
            SubmitTime = null;
            ReceiveTime = null;
            StartTime = null;
            FinishTime = null;
            Variables=new List<GlobalVariable>();
        }

        public static string SerializeVariables(List<GlobalVariable> vars)
        {
            XElement xe=new XElement("Variables");
            foreach(GlobalVariable var in vars)
            {
                XElement varXE=new XElement("Variable",
                    new XAttribute("Name",var.VarName),
                    new XAttribute("DataType",var.DataType.ToString()),
                    new XAttribute("Value",var.VarValue));
                xe.Add(varXE);
            }
            return xe.ToString();
        }

        public static List<GlobalVariable> InstantiateVariables(string xml)
        {
            XElement xe = XElement.Parse(xml);
            List<GlobalVariable> vars=new List<GlobalVariable>();
            foreach(XElement xeVar in xe.Elements("Variable"))
            {
                string varName = xeVar.Attribute("Name").Value;
                SimpleDataType dataType =
                    (SimpleDataType) Enum.Parse(typeof (SimpleDataType), xeVar.Attribute("DataType").Value);
                string varValue = xeVar.Attribute("Value").Value;
                GlobalVariable var=new GlobalVariable(varName,dataType,varValue);
                vars.Add(var);
            }
            return vars;
        }
    }
}
